import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'dart:convert';

import '../../services/preferences_service.dart';
import '../../services/database_service.dart';
import '../../services/tianyi_cloud_service.dart';
import '../../services/notification_service.dart';
import '../../services/sync_service.dart';
import '../../services/upload/upload_service.dart';
import '../../services/download/download_service.dart';

class SettingsController extends GetxController {
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  final DatabaseService _databaseService = Get.find<DatabaseService>();
  final TianyiCloudService _cloudService = Get.find<TianyiCloudService>();
  final NotificationService _notificationService = Get.find<NotificationService>();
  final SyncService _syncService = Get.find<SyncService>();
  final UploadService _uploadService = Get.find<UploadService>();
  final DownloadService _downloadService = Get.find<DownloadService>();
  
  // 主题设置
  final RxString _themeMode = 'system'.obs;
  String get themeMode => _themeMode.value;
  
  // 语言设置
  final RxString _language = 'zh_CN'.obs;
  String get language => _language.value;
  
  // 云同步设置
  final RxBool _autoSync = true.obs;
  bool get autoSync => _autoSync.value;
  
  final RxInt _syncInterval = 30.obs;
  int get syncInterval => _syncInterval.value;
  
  final RxInt _maxConcurrentUploads = 3.obs;
  int get maxConcurrentUploads => _maxConcurrentUploads.value;
  
  final RxInt _maxConcurrentDownloads = 3.obs;
  int get maxConcurrentDownloads => _maxConcurrentDownloads.value;
  
  final RxInt _chunkSize = 1024.obs;
  int get chunkSize => _chunkSize.value;
  
  // 文件管理设置
  final RxString _defaultDownloadPath = ''.obs;
  String get defaultDownloadPath => _defaultDownloadPath.value;
  
  final RxBool _showHiddenFiles = false.obs;
  bool get showHiddenFiles => _showHiddenFiles.value;
  
  final RxString _defaultSortBy = 'name'.obs;
  String get defaultSortBy => _defaultSortBy.value;
  
  final RxBool _sortAscending = true.obs;
  bool get sortAscending => _sortAscending.value;
  
  final RxString _defaultViewMode = 'list'.obs;
  String get defaultViewMode => _defaultViewMode.value;
  
  // 通知设置
  final RxBool _uploadNotifications = true.obs;
  bool get uploadNotifications => _uploadNotifications.value;
  
  final RxBool _downloadNotifications = true.obs;
  bool get downloadNotifications => _downloadNotifications.value;
  
  final RxBool _syncNotifications = true.obs;
  bool get syncNotifications => _syncNotifications.value;
  
  // 缓存设置
  final RxInt _maxCacheSize = 500.obs;
  int get maxCacheSize => _maxCacheSize.value;
  
  final RxBool _autoClearCache = true.obs;
  bool get autoClearCache => _autoClearCache.value;
  
  final RxInt _cacheRetentionDays = 7.obs;
  int get cacheRetentionDays => _cacheRetentionDays.value;
  
  // 安全设置
  final RxBool _biometricAuth = false.obs;
  bool get biometricAuth => _biometricAuth.value;
  
  final RxInt _autoLockTimeout = 5.obs;
  int get autoLockTimeout => _autoLockTimeout.value;
  
  // 网络设置
  final RxBool _wifiOnlySync = false.obs;
  bool get wifiOnlySync => _wifiOnlySync.value;
  
  final RxBool _wifiOnlyDownload = false.obs;
  bool get wifiOnlyDownload => _wifiOnlyDownload.value;
  
  // 存储信息
  final RxInt _usedStorage = 0.obs;
  int get usedStorage => _usedStorage.value;
  
  final RxInt _totalStorage = 0.obs;
  int get totalStorage => _totalStorage.value;
  
  final RxInt _cacheSize = 0.obs;
  int get cacheSize => _cacheSize.value;
  
  // 应用信息
  final RxString _appVersion = '1.0.0'.obs;
  String get appVersion => _appVersion.value;
  
  final RxString _buildNumber = '1'.obs;
  String get buildNumber => _buildNumber.value;
  
  @override
  void onInit() {
    super.onInit();
    _loadSettings();
    _loadStorageInfo();
  }
  
  // 加载设置
  Future<void> _loadSettings() async {
    try {
      // 主题和语言
      _themeMode.value = _preferencesService.getThemeMode();
      _language.value = _preferencesService.getLanguage();
      
      // 云同步设置
      _autoSync.value = _preferencesService.getAutoSync();
      _syncInterval.value = _preferencesService.getSyncInterval();
      _maxConcurrentUploads.value = _preferencesService.getMaxConcurrentUploads();
      _maxConcurrentDownloads.value = _preferencesService.getMaxConcurrentDownloads();
      _chunkSize.value = _preferencesService.getChunkSize();
      
      // 文件管理设置
      _defaultDownloadPath.value = _preferencesService.getDefaultDownloadPath();
      _showHiddenFiles.value = _preferencesService.getShowHiddenFiles();
      _defaultSortBy.value = _preferencesService.getDefaultSortBy();
      _sortAscending.value = _preferencesService.getSortAscending();
      _defaultViewMode.value = _preferencesService.getDefaultViewMode();
      
      // 通知设置
      _uploadNotifications.value = _preferencesService.getUploadNotifications();
      _downloadNotifications.value = _preferencesService.getDownloadNotifications();
      _syncNotifications.value = _preferencesService.getSyncNotifications();
      
      // 缓存设置
      _maxCacheSize.value = _preferencesService.getMaxCacheSize();
      _autoClearCache.value = _preferencesService.getAutoClearCache();
      _cacheRetentionDays.value = _preferencesService.getCacheRetentionDays();
      
      // 安全设置
      _biometricAuth.value = _preferencesService.getBiometricAuth();
      _autoLockTimeout.value = _preferencesService.getAutoLockTimeout();
      
      // 网络设置
      _wifiOnlySync.value = _preferencesService.getWifiOnlySync();
      _wifiOnlyDownload.value = _preferencesService.getWifiOnlyDownload();
      
    } catch (e) {
      _showError('加载设置失败', e.toString());
    }
  }
  
  // 加载存储信息
  Future<void> _loadStorageInfo() async {
    try {
      final storageInfo = await _cloudService.getStorageInfo();
      _usedStorage.value = storageInfo['used'] ?? 0;
      _totalStorage.value = storageInfo['total'] ?? 0;
      
      // 获取缓存大小
      _cacheSize.value = await _getCacheSize();
      
    } catch (e) {
      print('加载存储信息失败: $e');
    }
  }
  
  // 获取缓存大小
  Future<int> _getCacheSize() async {
    try {
      // 这里应该计算实际的缓存大小
      // 暂时返回模拟数据
      return 50 * 1024 * 1024; // 50MB
    } catch (e) {
      return 0;
    }
  }
  
  // 设置主题模式
  Future<void> setThemeMode(String mode) async {
    try {
      await _preferencesService.setThemeMode(mode);
      _themeMode.value = mode;
      
      // 应用主题
      _applyTheme(mode);
      
      _showSuccess('主题设置已保存');
    } catch (e) {
      _showError('设置主题失败', e.toString());
    }
  }
  
  // 应用主题
  void _applyTheme(String mode) {
    switch (mode) {
      case 'light':
        Get.changeThemeMode(ThemeMode.light);
        break;
      case 'dark':
        Get.changeThemeMode(ThemeMode.dark);
        break;
      case 'system':
      default:
        Get.changeThemeMode(ThemeMode.system);
        break;
    }
  }
  
  // 设置语言
  Future<void> setLanguage(String lang) async {
    try {
      await _preferencesService.setLanguage(lang);
      _language.value = lang;
      
      // 应用语言
      _applyLanguage(lang);
      
      _showSuccess('语言设置已保存');
    } catch (e) {
      _showError('设置语言失败', e.toString());
    }
  }
  
  // 应用语言
  void _applyLanguage(String lang) {
    Locale locale;
    switch (lang) {
      case 'en_US':
        locale = const Locale('en', 'US');
        break;
      case 'zh_CN':
      default:
        locale = const Locale('zh', 'CN');
        break;
    }
    Get.updateLocale(locale);
  }
  
  // 设置自动同步
  Future<void> setAutoSync(bool enabled) async {
    try {
      await _preferencesService.setAutoSync(enabled);
      _autoSync.value = enabled;
      
      if (enabled) {
        await _syncService.startAutoSync();
      } else {
        await _syncService.stopAutoSync();
      }
      
      _showSuccess(enabled ? '自动同步已开启' : '自动同步已关闭');
    } catch (e) {
      _showError('设置自动同步失败', e.toString());
    }
  }
  
  // 设置同步间隔
  Future<void> setSyncInterval(int minutes) async {
    try {
      await _preferencesService.setSyncInterval(minutes);
      _syncInterval.value = minutes;
      
      // 重启自动同步以应用新间隔
      if (_autoSync.value) {
        await _syncService.startAutoSync();
      }
      
      _showSuccess('同步间隔已设置为 $minutes 分钟');
    } catch (e) {
      _showError('设置同步间隔失败', e.toString());
    }
  }
  
  // 设置最大并发上传数
  Future<void> setMaxConcurrentUploads(int count) async {
    try {
      await _preferencesService.setMaxConcurrentUploads(count);
      _maxConcurrentUploads.value = count;
      _showSuccess('最大并发上传数已设置为 $count');
    } catch (e) {
      _showError('设置并发上传数失败', e.toString());
    }
  }
  
  // 设置最大并发下载数
  Future<void> setMaxConcurrentDownloads(int count) async {
    try {
      await _preferencesService.setMaxConcurrentDownloads(count);
      _maxConcurrentDownloads.value = count;
      _showSuccess('最大并发下载数已设置为 $count');
    } catch (e) {
      _showError('设置并发下载数失败', e.toString());
    }
  }
  
  // 设置分块大小
  Future<void> setChunkSize(int size) async {
    try {
      await _preferencesService.setChunkSize(size);
      _chunkSize.value = size;
      _showSuccess('分块大小已设置为 ${size}KB');
    } catch (e) {
      _showError('设置分块大小失败', e.toString());
    }
  }
  
  // 选择下载路径
  Future<void> selectDownloadPath() async {
    try {
      final result = await FilePicker.platform.getDirectoryPath();
      if (result != null) {
        await _preferencesService.setDefaultDownloadPath(result);
        _defaultDownloadPath.value = result;
        _showSuccess('下载路径已设置');
      }
    } catch (e) {
      _showError('选择下载路径失败', e.toString());
    }
  }
  
  // 设置显示隐藏文件
  Future<void> setShowHiddenFiles(bool show) async {
    try {
      await _preferencesService.setShowHiddenFiles(show);
      _showHiddenFiles.value = show;
      _showSuccess(show ? '已显示隐藏文件' : '已隐藏隐藏文件');
    } catch (e) {
      _showError('设置显示隐藏文件失败', e.toString());
    }
  }
  
  // 设置默认排序方式
  Future<void> setDefaultSortBy(String sortBy) async {
    try {
      await _preferencesService.setDefaultSortBy(sortBy);
      _defaultSortBy.value = sortBy;
      _showSuccess('默认排序方式已设置');
    } catch (e) {
      _showError('设置排序方式失败', e.toString());
    }
  }
  
  // 设置排序顺序
  Future<void> setSortAscending(bool ascending) async {
    try {
      await _preferencesService.setSortAscending(ascending);
      _sortAscending.value = ascending;
      _showSuccess(ascending ? '设置为升序排列' : '设置为降序排列');
    } catch (e) {
      _showError('设置排序顺序失败', e.toString());
    }
  }
  
  // 设置默认视图模式
  Future<void> setDefaultViewMode(String mode) async {
    try {
      await _preferencesService.setDefaultViewMode(mode);
      _defaultViewMode.value = mode;
      _showSuccess('默认视图模式已设置');
    } catch (e) {
      _showError('设置视图模式失败', e.toString());
    }
  }
  
  // 设置上传通知
  Future<void> setUploadNotifications(bool enabled) async {
    try {
      await _preferencesService.setUploadNotifications(enabled);
      _uploadNotifications.value = enabled;
      _showSuccess(enabled ? '上传通知已开启' : '上传通知已关闭');
    } catch (e) {
      _showError('设置上传通知失败', e.toString());
    }
  }
  
  // 设置下载通知
  Future<void> setDownloadNotifications(bool enabled) async {
    try {
      await _preferencesService.setDownloadNotifications(enabled);
      _downloadNotifications.value = enabled;
      _showSuccess(enabled ? '下载通知已开启' : '下载通知已关闭');
    } catch (e) {
      _showError('设置下载通知失败', e.toString());
    }
  }
  
  // 设置同步通知
  Future<void> setSyncNotifications(bool enabled) async {
    try {
      await _preferencesService.setSyncNotifications(enabled);
      _syncNotifications.value = enabled;
      _showSuccess(enabled ? '同步通知已开启' : '同步通知已关闭');
    } catch (e) {
      _showError('设置同步通知失败', e.toString());
    }
  }
  
  // 设置最大缓存大小
  Future<void> setMaxCacheSize(int sizeMB) async {
    try {
      await _preferencesService.setMaxCacheSize(sizeMB);
      _maxCacheSize.value = sizeMB;
      _showSuccess('最大缓存大小已设置为 ${sizeMB}MB');
    } catch (e) {
      _showError('设置缓存大小失败', e.toString());
    }
  }
  
  // 设置自动清理缓存
  Future<void> setAutoClearCache(bool enabled) async {
    try {
      await _preferencesService.setAutoClearCache(enabled);
      _autoClearCache.value = enabled;
      _showSuccess(enabled ? '自动清理缓存已开启' : '自动清理缓存已关闭');
    } catch (e) {
      _showError('设置自动清理缓存失败', e.toString());
    }
  }
  
  // 设置缓存保留天数
  Future<void> setCacheRetentionDays(int days) async {
    try {
      await _preferencesService.setCacheRetentionDays(days);
      _cacheRetentionDays.value = days;
      _showSuccess('缓存保留天数已设置为 $days 天');
    } catch (e) {
      _showError('设置缓存保留天数失败', e.toString());
    }
  }
  
  // 清理缓存
  Future<void> clearCache() async {
    try {
      await _preferencesService.clearCache();
      _cacheSize.value = 0;
      _showSuccess('缓存已清理');
    } catch (e) {
      _showError('清理缓存失败', e.toString());
    }
  }
  
  // 设置生物识别认证
  Future<void> setBiometricAuth(bool enabled) async {
    try {
      await _preferencesService.setBiometricAuth(enabled);
      _biometricAuth.value = enabled;
      _showSuccess(enabled ? '生物识别认证已开启' : '生物识别认证已关闭');
    } catch (e) {
      _showError('设置生物识别认证失败', e.toString());
    }
  }
  
  // 设置自动锁定超时
  Future<void> setAutoLockTimeout(int minutes) async {
    try {
      await _preferencesService.setAutoLockTimeout(minutes);
      _autoLockTimeout.value = minutes;
      _showSuccess('自动锁定超时已设置为 $minutes 分钟');
    } catch (e) {
      _showError('设置自动锁定超时失败', e.toString());
    }
  }
  
  // 设置仅WiFi同步
  Future<void> setWifiOnlySync(bool enabled) async {
    try {
      await _preferencesService.setWifiOnlySync(enabled);
      _wifiOnlySync.value = enabled;
      _showSuccess(enabled ? '仅WiFi同步已开启' : '仅WiFi同步已关闭');
    } catch (e) {
      _showError('设置仅WiFi同步失败', e.toString());
    }
  }
  
  // 设置仅WiFi下载
  Future<void> setWifiOnlyDownload(bool enabled) async {
    try {
      await _preferencesService.setWifiOnlyDownload(enabled);
      _wifiOnlyDownload.value = enabled;
      _showSuccess(enabled ? '仅WiFi下载已开启' : '仅WiFi下载已关闭');
    } catch (e) {
      _showError('设置仅WiFi下载失败', e.toString());
    }
  }
  
  // 导出设置
  Future<void> exportSettings() async {
    try {
      final settings = await _preferencesService.exportSettings();
      
      final result = await FilePicker.platform.saveFile(
        dialogTitle: '导出设置',
        fileName: 'snail_netdisk_settings_${DateTime.now().millisecondsSinceEpoch}.json',
        type: FileType.custom,
        allowedExtensions: ['json'],
      );
      
      if (result != null) {
        final file = File(result);
        await file.writeAsString(jsonEncode(settings));
        _showSuccess('设置已导出到: $result');
      }
    } catch (e) {
      _showError('导出设置失败', e.toString());
    }
  }
  
  // 导入设置
  Future<void> importSettings() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['json'],
        allowMultiple: false,
      );
      
      if (result != null && result.files.single.path != null) {
        final file = File(result.files.single.path!);
        final content = await file.readAsString();
        final settings = jsonDecode(content) as Map<String, dynamic>;
        
        await _preferencesService.importSettings(settings);
        await _loadSettings(); // 重新加载设置
        
        _showSuccess('设置已导入');
      }
    } catch (e) {
      _showError('导入设置失败', e.toString());
    }
  }
  
  // 重置所有设置
  Future<void> resetAllSettings() async {
    try {
      // 显示确认对话框
      final confirmed = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('重置设置'),
          content: const Text('确定要重置所有设置吗？此操作不可撤销。'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('确定'),
            ),
          ],
        ),
      );
      
      if (confirmed == true) {
        await _preferencesService.clearAllSettings();
        await _loadSettings(); // 重新加载默认设置
        _showSuccess('所有设置已重置');
      }
    } catch (e) {
      _showError('重置设置失败', e.toString());
    }
  }
  
  // 获取应用信息
  Map<String, dynamic> getAppInfo() {
    return {
      'app_name': 'Snail NetDisk',
      'version': _appVersion.value,
      'build_number': _buildNumber.value,
      'platform': Platform.operatingSystem,
      'platform_version': Platform.operatingSystemVersion,
    };
  }
  
  // 获取存储使用情况
  Map<String, dynamic> getStorageUsage() {
    final usedPercent = _totalStorage.value > 0 
        ? (_usedStorage.value / _totalStorage.value * 100).round()
        : 0;
    
    return {
      'used_storage': _usedStorage.value,
      'total_storage': _totalStorage.value,
      'free_storage': _totalStorage.value - _usedStorage.value,
      'used_percent': usedPercent,
      'cache_size': _cacheSize.value,
    };
  }
  
  // 格式化存储大小
  String formatStorageSize(int bytes) {
    if (bytes < 1024) {
      return '${bytes}B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)}KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
    }
  }
  
  // 刷新存储信息
  Future<void> refreshStorageInfo() async {
    await _loadStorageInfo();
  }
  
  // 显示成功信息
  void _showSuccess(String message) {
    Get.snackbar(
      '成功',
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 2),
    );
  }
  
  // 显示错误信息
  void _showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
}